# -*- coding: utf-8 -*-

import scrapy
import time
import random
import pymysql
from scrapy.utils.project import get_project_settings

class DB(object):

    def __new__(cls, *args, **kw):  
        if not hasattr(cls, '_instance'):  
            o = super(DB, cls)  
            cls._instance = o.__new__(cls, *args, **kw)  
        return cls._instance 

    def __init__(self):
        settings = get_project_settings()
        self.conn = pymysql.connect(host=settings['MYSQL_HOST'], 
                                    port=3306, 
                                    user=settings['MYSQL_USER'], 
                                    passwd=settings['MYSQL_PASSWD'], 
                                    db=settings['MYSQL_DBNAME'],
                                    charset=settings['MYSQL_CHARSET'])
        self.cursor = self.conn.cursor()
        self.cursor.execute('SET NAMES utf8;')

    def save_article(self, item):

        item['title'] = pymysql.escape_string(item['title'])
        item['content'] = pymysql.escape_string(item['content'])
        item['summary'] = pymysql.escape_string(item['summary'])

        update_time = add_time = int(time.time())
        read_count_random = random.randint(0, 100)
        admin_user_id = 1
        is_active = 0
        sql = "INSERT INTO `md_article` (`title`, `summary`, `content`, `source`, `img_url`, `read_count_random`, `is_active`, `admin_user_id`, `update_time`, `add_time`, `source_url`) VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')" % (item['title'], item['summary'], item['content'], item['source'], item['img_url'], read_count_random, is_active, admin_user_id, update_time, add_time, item['source_url'])
        #print(sql)
        self.cursor.execute(sql)
        self.conn.commit()

    def __del__(self):
        self.cursor.close()
        self.conn.close()